package org.jeecg.modules.demo.hd.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.demo.hd.entity.AppNews;
import org.jeecg.modules.demo.hd.service.IAppNewsService;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: app_news
 * @Author: jeecg-boot
 * @Date: 2025-04-26
 * @Version: V1.0
 */
@Api(tags = "新闻")
@RestController
@RequestMapping("/hd/appNews")
@Slf4j
public class AppNewsController extends JeecgController<AppNews, IAppNewsService> {
    @Autowired
    private IAppNewsService appNewsService;

    /**
     * 分页列表查询
     *
     * @param appNews
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "app_news-分页列表查询")
    @ApiOperation(value = "分页获取新闻列表", notes = "分页获取新闻列表")
    @GetMapping(value = "/list")
    public Result<IPage<AppNews>> queryPageList(AppNews appNews,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        LambdaQueryWrapper<AppNews> queryWrapper = Wrappers.lambdaQuery();// QueryGenerator.initQueryWrapper(appNews, req.getParameterMap());
        queryWrapper.orderByDesc(AppNews::getTime);
        Page<AppNews> page = new Page<AppNews>(pageNo, pageSize);
        IPage<AppNews> pageList = appNewsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param appNews
     * @return
     */
    @AutoLog(value = "app_news-添加")
    @ApiOperation(value = "app_news-添加", notes = "app_news-添加")
    @RequiresPermissions("hd:app_news:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody AppNews appNews) {
        appNewsService.save(appNews);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param appNews
     * @return
     */
    @AutoLog(value = "app_news-编辑")
    @ApiOperation(value = "app_news-编辑", notes = "app_news-编辑")
    @RequiresPermissions("hd:app_news:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody AppNews appNews) {
        appNewsService.updateById(appNews);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "app_news-通过id删除")
    @ApiOperation(value = "app_news-通过id删除", notes = "app_news-通过id删除")
    @RequiresPermissions("hd:app_news:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        appNewsService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "app_news-批量删除")
    @ApiOperation(value = "app_news-批量删除", notes = "app_news-批量删除")
    @RequiresPermissions("hd:app_news:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.appNewsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "app_news-通过id查询")
    @ApiOperation(value = "获取新闻详情", notes = "获取新闻详情")
    @GetMapping(value = "/queryById")
    public Result<AppNews> queryById(@RequestParam(name = "id", required = true) String id) {
        AppNews appNews = appNewsService.getById(id);
        if (appNews == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(appNews);
    }


    @ApiOperation(value = "API更新新闻", notes = "API更新新闻")
    @GetMapping(value = "/updateNews")
    public Result<String> updateNews() {
        String url = "https://api.tanshuapi.com/api/toutiao/v1/index?key=5ca2d173207e9975ad458128efdbeec8&type=&num=40&start=0";
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            // 设置请求属性
            con.setRequestMethod("GET");
            con.setRequestProperty("Content-Type", "application/json");
            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 200
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // 解析JSON获取access_token
                String strData = response.toString();
                JSONObject parse = JSONObject.parseObject(strData);
                String data = parse.get("data").toString();
                JSONObject jsonObject = JSONObject.parseObject(data);
                String strList = jsonObject.get("list").toString();
                List<AppNews> appNews = JSONObject.parseArray(strList, AppNews.class);
                this.appNewsService.saveBatch(appNews);
            } else {
                throw new Exception("Error while fetching access token. Response Code: " + responseCode);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.OK("");
    }
}
